package com.net.framework.help.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.widget.TextView;

/**
 * Author：xiaobin.zhang
 * Email：154722566@qq.com
 * Date：2017/1/9 10:29
 * Desc：<--功能描述-->
 */
public class TextViewCenterImageSpan {

    public static void textViewImageSpan(Context context, TextView textView, int drawableRes, String content) {
        CenterImageSpan imgSpan = new CenterImageSpan(context, drawableRes);
        SpannableString spanString = new SpannableString("icon ");
        spanString.setSpan(imgSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spanString);
        textView.append(content);
    }

    public static class CenterImageSpan extends ImageSpan {
        public CenterImageSpan(Context context, final int drawableRes) {
            super(context, drawableRes);
        }

        @Override
        public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
            // image to draw
            Drawable b = getDrawable();
            // font metrics of text to be replaced
            Paint.FontMetricsInt fm = paint.getFontMetricsInt();
            int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;
            canvas.save();
            canvas.translate(x, transY);
            b.draw(canvas);
            canvas.restore();
        }
    }
}